﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace ComicsEditor
{
    public class FrameOrderInstrument : Instrument
    {
        public Color ActiveColor = Color.Cyan;
        public Color SelectedColor = Color.Blue;

        public int Current = -1;

        private List<Text> numbers = new List<Text>();

        public FrameOrderInstrument()
        {
        }

        public override void Enable()
        {
            base.Enable();
            
            for (int i = 0; i < pageInfo.Frames.Count; i++)
            {
                Text text = new Text(Page, Point.Empty);
                text.FontName = "Serif";
                text.FontSize = 36;
                text.Bold = true;
                text.Baseline = "text-before-edge";
                text.Fill = new SolidBrush(ActiveColor);
                text.DoNotScale = true;
                numbers.Add(text);
            }
            SetText(0);

            Current = -1;
        }

        public override void Disable()
        {
            foreach (Text text in numbers)
                text.Dispose();
            numbers.Clear();
            base.Disable();
        }

        public override bool Activate(Point point, out Point offset)
        {
            offset = Point.Empty;
            int i;
            for (i = Current + 1; i < pageInfo.Frames.Count && !pageInfo.Frames[i].Rectangle.Contains(point); i++);
            if (i >= pageInfo.Frames.Count)
                return false;
            Current++;
            while (i > Current)
            {
                Frame temp = pageInfo.Frames[i];
                pageInfo.Frames[i] = pageInfo.Frames[i - 1];
                pageInfo.Frames[i - 1] = temp;
                i--;
            }
            (numbers[Current].Fill as SolidBrush).Color = SelectedColor;
            SetText(Current);

            if (Current == pageInfo.Frames.Count - 1)
            {
                Current = -1;
                foreach (Text text in numbers)
                    (text.Fill as SolidBrush).Color = ActiveColor;
            }
            return true;
        }

        private void SetText(int from)
        {
            for (int i = from; i < pageInfo.Frames.Count; i++)
            {
                Frame frame = pageInfo.Frames[i];
                numbers[i].Position = new Point(frame.Rectangle.X + 10, frame.Rectangle.Y);
                numbers[i].Formatted.Value = (i + 1).ToString();
            }
        }
    }
}
